In [1]:
# nametuple 举例
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
print(p.x, p.y)
In [2]:
i = p.x + p.y
print(i)
In [3]:
# nametuple 举例
from collections import namedtuple
Web = namedtuple('web', ['name', 'type', 'url'])
p1 = Web('google', 'search', 'www.google.com')
p2 = Web('sina', 'portal', 'www.sina.com.cn')
print(p1)
In [4]:
print(p1.name, p1.url)
In [5]:
print(p1.url, p2.url)
In [6]:
# 遍历 nametuple
for i in p2:
print(i)
In [7]:
# 复杂的基于 namedtuple list demo
from collections import namedtuple
Web = namedtuple('web', ['name', 'type', 'url'])
p = []
p.append(Web('google', 'search', 'www.google.com'))
p.append(Web('sina', 'portal', 'www.sina.com.cn'))
print(p)
for i in p:
print(i.name)
In [8]:
# 显示 namedtuple 的字段名称
print(Web._fields)
In [21]:
# deque 举例
from collections import deque
q = deque(['a', 'b', 'c'])
q.append('x')
q.appendleft('y')
print(q)
In [6]:
# 对比 list 和 deque 的速度
from collections import deque
import time
# list
q0 = [x*x for x in range(10000000)]
# list
a = time.time()
q0.insert(0,888)
# q0.append(999)
b = time.time()
print(b-a)
# 生成 deque
q1= deque(q0)
# deque
a = time.time()
q1.appendleft(888)
# q1.append(999)
b = time.time()
print('%2.8f' % (b-a))
In [16]:
from collections import deque
l = ['a','b','c','d']
l = deque(l)
print(l)
In [9]:
# deque rotation
l = ['a','b','c','d','e']
l = deque(l)
l.rotate(2)
print(l)
l.rotate(-2)
print(l)
In [13]:
# deque pop() 同样可以区分头尾
l = deque(['a','b','c'])
l.pop()
print(l)
In [14]:
l = deque(['a','b','c'])
l.popleft()
print(l)
In [22]:
# 标准的字典用法
i = {'name':'David'}
print(i['name'])
In [23]:
# 不存在 key,则会报错
i = {'name':'David'}
print(i['score'])
In [7]:
# defaultdict 举例
from collections import defaultdict
d = defaultdict(lambda: 100)
d['name']='David'
print(d['name'])
In [8]:
# default 返回默认值,不会报错
print(d['score'])
print(d['best_score'])
In [9]:
from collections import defaultdict
d = defaultdict(lambda: '100')
d['name']='David'
print(d['name'])
print(d['score'])
In [10]:
# dict 是无序的
d = dict([('a', 1), ('b', 2), ('c', 3)])
print(d)
In [11]:
# 传统dict 追加一对 key value
d = dict([('a', 1), ('b', 2), ('c', 3)])
print(d)
d['d'] = 4
print(d)
In [3]:
# 使用 OrderedDict
from collections import OrderedDict
d = OrderedDict()
d['a'] = 1
d['b'] = 2
d['c'] = 3
print(d)
In [45]:
# 使用 OrderedDict, 追加一对 key value
# OrderedDict 的 key 会按照插入的顺序排列,不是 key 本身排序
from collections import OrderedDict
d = OrderedDict()
d['a'] = 1
d['b'] = 2
d['c'] = 3
print(d)
d['d'] = 4
print(d)
In [12]:
# OrderedDict可以实现一个FIFO(先进先出)的dict,当容量超出限制时,先删除最早添加的Key:
from collections import OrderedDict
class LastUpdatedOrderedDict(OrderedDict):
def __init__(self, capacity):
super(LastUpdatedOrderedDict, self).__init__()
self._capacity = capacity
def __setitem__(self, key, value):
containsKey = 1 if key in self else 0
if len(self) - containsKey >= self._capacity:
last = self.popitem(last=False)
print('remove:', last)
if containsKey:
del self[key]
print('set:', (key, value))
else:
print('add:', (key, value))
OrderedDict.__setitem__(self, key, value)
d = LastUpdatedOrderedDict(4)
d['a'] = 1
d['b'] = 2
d['c'] = 3
print(d)
In [13]:
d['d'] = 4
d['e'] = 5
d['f'] = 6
print(d)
In [15]:
# 简化的先进先出Dict
from collections import OrderedDict
d = OrderedDict()
d['a'] = 1
d['b'] = 2
d['c'] = 3
print(d)
# 3个参数:原始有序字典,容量限制,待插入的key,待插入的value
def update_ordereddict(ordered_dict, len_limit ,key, value):
if len(ordered_dict) >=0 and len(ordered_dict) < len_limit:
ordered_dict[key]=value
return ordered_dict
else:
ordered_dict.popitem(last=False)
ordered_dict[key]=value
return ordered_dict
# 插入一个新key-value
update_ordereddict(d, 3, 'new_key', 4)
Out[15]:
In [26]:
# Counter类的目的是用来跟踪值出现的次数,以字典的键值对形式存储,其中元素作为key,其计数作为value
# 下面这个例子就是使用 Counter 模块统计一段句子里面所有字符出现次数
from collections import Counter
s = 'A Counter is a dict subclass. '.lower()
c = Counter(s)
# 获取出现频率最高的5个字符
print(c.most_common(5))
In [18]:
# 是否可以统计中文呢?
s = '他会自己长大远去我们也各自远去'
c = Counter(s)
print(c.most_common(5))
In [24]:
# Counter 举例,用户输入内容
from collections import Counter
s = input('Please input:')
s = s.lower()
c = Counter(s)
# 获取出现频率最高的5个字符
print(c.most_common(5))
In [37]:
# 读出 Counter 对象中的key 和value
s = 'A Counter is a dict subclass. '.lower()
c = Counter(s)
# 用列表生成式获得 counter 中的 key
list1 = [k for k,v in c.most_common()]
# 用列表生成式获得 counter 中的 value
list2 = [v for k,v in c.most_common()]
print(list1)
print(list2)
In [38]:
# 我们在 notebook 中画个图
import matplotlib.pyplot as plt
plt.bar(range(len(list2)), list2,color='rgb',tick_label=list1)
plt.show()
In [6]:
# 看似健壮的程序,输入字母会报错
a = int(input('a:'))
if a ==0:
print("you cannot input 0")
else:
r = 10 / a
print('result:', r)
In [5]:
# 防止输入0作为除数
try:
a = int(input('a:'))
r = 10 / a
print('result:', r)
except ZeroDivisionError as e:
print('except:',e)
In [13]:
a = int(input('a:'))
r = 10 / a
In [10]:
# 如何捕捉多个类型的错误?
try:
a = int(input('a:'))
r = 10 / a
print('result:', r)
except ZeroDivisionError as e:
print('except:',e)
except ValueError as e:
print('except:',e)
In [11]:
# try...except...finally
a = int(input('a:'))
try:
r = 10 / a
print('result:', r)
except ZeroDivisionError as e:
print('except:', e)
finally:
print('finish...')
In [69]:
# 防止错误举例
a = 100
try:
b = a + c
print(b)
except NameError as e:
print('except:',e)
In [1]:
# 对 int 进行判断
a = input('a:')
# 对输入值转换还有更完善的方法,设定一个转换结果
try:
a = int(a)
except ValueError as e:
print('except:', e)
a = 1
finally:
print('covert ok')
try:
r = 10 / a
print('result:', r)
except ZeroDivisionError as e:
print('except:', e)
finally:
print('finish...')
In [ ]: